package com.zx.dao.impl;

import com.zx.dao.AdminDao;
import com.zx.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;


public class AdminDaoImpl  implements AdminDao {
    public static final String SQL_UPDATE_LOGIN_TIME = "update admin  set logintime=?,loginip=? where username=?" ;
    public static final String SQL_LOGIN="select ID from admin where username=? and password=?";

    /**
     * 根据用户名,更新登陆时间 ip
     *
     * @param username
     *
     * @param date
     * @param ip
     */
    @Override
    public void updateLoginTime(String username, Date date, String ip) {
        //获取连接
        Connection connection = DruidUtil.getConnection();
        //预编译SQL语句
        PreparedStatement state=null;
        try {
            state = connection.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            state.setDate(1, new java.sql.Date(date.getTime()));
            state.setString(2, ip);
            state.setString(3, username);
            state.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(connection, state, null);
        }


    }

    /**
     * 管理员根据账号密码登陆
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public boolean login(String username, String password) {
        //获取连接
        Connection connection = DruidUtil.getConnection();
        //预编译SQL语句
        PreparedStatement state=null;

        ResultSet resultSet=null;
        try {
            state = connection.prepareStatement(SQL_LOGIN);
            state.setString(1, username);
            state.setString(2, password);
        //拿到结果集,向上抽取
             resultSet = state.executeQuery();
              return resultSet.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(connection, state, null);
        }

        return false;

    }
}
